﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using CKEditor.Services;
using Orchard.FileSystems.VirtualPath;
using Orchard.Themes.Services;
using Orchard;
using CKEditor.Models;
using Orchard.ContentManagement;
using System.Web.Mvc;
using Orchard.Environment.Extensions;

namespace CKEditor.Providers
{
    public class DefaultConfigProvider : ICKEditorConfigProvider
    {
        private readonly ISiteThemeService _siteThemeService;
        private readonly IVirtualPathProvider _virtualPathProvider;
        private readonly IExtensionManager _extensionManager;
        private readonly IEnumerable<ICKEditorPlugin> _ckEditorPlugins;
        public IOrchardServices Services { get; set; }

        public DefaultConfigProvider(
            IOrchardServices orchardServices,
            ISiteThemeService siteThemeService,
            IVirtualPathProvider virtualPathProvider,
            IExtensionManager extensionManager,
            IEnumerable<ICKEditorPlugin> ckEditorPlugins
            )
        {

            _siteThemeService = siteThemeService;
            _virtualPathProvider = virtualPathProvider;
            _extensionManager = extensionManager;
            Services = orchardServices;
            _ckEditorPlugins = ckEditorPlugins;
        }

        public void PopulateConfiguration(CKEditorConfigContext config)
        {
            // Get CKEditor settings
            var ckSettings = Services.WorkContext.CurrentSite.As<CKEditorSettingsPart>();
            if (ckSettings != null)
            {
                if (!String.IsNullOrWhiteSpace(ckSettings.ContentsCss))
                {

                    // Push css link(s) into config
                    var currentTheme = _siteThemeService.GetSiteTheme();
                    var sheets =
                        // Get list of stylesheets
                        ckSettings.ContentsCss.Split(new[] { ' ', ',' }, StringSplitOptions.RemoveEmptyEntries)
                        // Transform to full URLs
                        .Select(sheet => FindStyleLocation(sheet, currentTheme))
                        .Where(path => path != null).ToList(); // Execute at this time to avoid trouble later
                    config.Add(new CKEditorConfigStringList("contentsCss", sheets));
                }
                if (!String.IsNullOrWhiteSpace(ckSettings.ExtraPlugins))
                {
                    // TODO: Plugins should add modularly from an ICKEditorPlugin interface?
                    var plugins =
                        ckSettings.ExtraPlugins;
                    /*.Split(new[] { ' ', ',' }, StringSplitOptions.RemoveEmptyEntries);
                    foreach (var plugin in _ckEditorPlugins)
                    {
                        if (plugins.Contains(plugin.PluginName))
                        {
                            if (plugin.BasePath != null)
                            {
                            }
                        }
                    }*/

                    config.Add(new CKEditorConfigString("extraPlugins", plugins));
                }
                // For removing standard styles if stylesheet parser is used
                if (ckSettings.ClearDefaultStyleSets)
                {
                    config.Add(new CKEditorConfigStringList("stylesSet", Enumerable.Empty<String>()));
                }

            }
        }

        protected string FindStyleLocation(string sheet, Orchard.Environment.Extensions.Models.ExtensionDescriptor currentTheme)
        {
            var testLocation = string.Format("{0}/{1}/Styles/{2}", currentTheme.Location, currentTheme.Id, sheet);
            if (_virtualPathProvider.FileExists(testLocation)) {
                return UrlHelper.GenerateContentUrl(testLocation, Services.WorkContext.HttpContext);
            }
            // Traverse base theme if applicable
            if (!String.IsNullOrWhiteSpace(currentTheme.BaseTheme))
            {
                var subTheme = _extensionManager.GetExtension(currentTheme.BaseTheme);
                if (subTheme != null) return FindStyleLocation(sheet, subTheme);
            }
            return null;
        }

    }
}